package code.rocky.threadlocal;

import java.util.concurrent.TimeUnit;

public class ThreadLocalDemo01 {

    ThreadLocal<String> threadLocal = new ThreadLocal<String>();

    public static void main(String[] args) {
        ThreadLocalDemo01 threadLocalTest = new ThreadLocalDemo01();
        threadLocalTest.showTwoThread();
    }

    public void showTwoThread() {
        new Thread(new Runnable() {
            public void run() {
                testQuarantine();
            }
        },"t1").start();

        new Thread(new Runnable() {
            public void run() {
                testQuarantine();
            }
        },"t2").start();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void testQuarantine() {
        System.out.println(Thread.currentThread().getName() + " 线程未设置之前: " + threadLocal.get());
        threadLocal.set(Thread.currentThread().getName());
        try {
            System.out.println("线程: " + Thread.currentThread().getName() + " 已放入到 threadLocal");
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()  + " 线程设置之后: " + threadLocal.get());
    }
}
